/**
 * 
 */
package de.hft_stuttgart.dsa.ctt.reader;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import de.hft_stuttgart.dsa.ctt.model.Course;
import de.hft_stuttgart.dsa.ctt.model.CourseAssignmentMatrix;
import de.hft_stuttgart.dsa.ctt.model.Period;
import de.hft_stuttgart.dsa.ctt.model.ProblemInstance;
import de.hft_stuttgart.dsa.ctt.model.Room;

/**
 * @author Ali Yuruz
 * 
 */
public class OutputReader {
	public CourseAssignmentMatrix generateMatrixFromOutput(
			String outputFilePath, String problemDataset) {

		DatasetReader datasetReader = new DatasetReader();
		ProblemInstance pInstance = datasetReader.readDataset(problemDataset);
		CourseAssignmentMatrix cAssignmentMatrix = new CourseAssignmentMatrix(
				pInstance.getRooms(), pInstance.getPeriods());
		HashMap<String, Integer> roomIdMap = createRoomIdMap(pInstance
				.getRooms());

		Course[][] courseMatrix = (Course[][]) cAssignmentMatrix
				.getPeriodRoomMatrix();
		HashMap<String, Course> allCourses = pInstance.getAllCourses();

		try {
			BufferedReader inputStream = new BufferedReader(new FileReader(
					outputFilePath));
			String line;
			String currentRoomId;
			String currentCourseId;
			Course currentCourse;
			int periodOfDay;
			int dayOfWeek;
			int currentPeriod;

			String[] lineElements;
			while ((line = inputStream.readLine()) != null) {
				lineElements = line.split(" ");
				currentCourseId = lineElements[0];
				currentRoomId = lineElements[1];
				periodOfDay = Integer.parseInt(lineElements[3]);
				dayOfWeek = Integer.parseInt(lineElements[2]);
				currentPeriod = Period.getCalculatedPeriod(pInstance
						.getPeriodsPerDay(), periodOfDay, dayOfWeek);
				currentCourse = allCourses.get(currentCourseId);				
				courseMatrix[currentPeriod][roomIdMap.get(currentRoomId)] = currentCourse;
			}
		} catch (IOException ie) {
			ie.printStackTrace();
		}
		return cAssignmentMatrix;

	}

	private HashMap<String, Integer> createRoomIdMap(List<Room> rooms) {
		HashMap<String, Integer> roomMap = new HashMap<String, Integer>();
		int roomIndex = 0;
		for (Room room : rooms) {
			roomMap.put(room.getRoomId(), roomIndex);			
			roomIndex++;
		}
		return roomMap;
	}
}